import { _decorator, Collider2D, Component, math, Node, Quat, RigidBody2D, Animation, sp, v2, Vec2, Contact2DType, IPhysics2DContact, log, Vec3 } from 'cc';
import { PlayerStateMachine } from './PlayerStateMachine';
import { VirtualInput } from '../VirtualInput';
import { PlayerMoveState } from './PlayerMoveState';
import { mathutil } from '../util/MathUtil';
import { Entity } from '../Entity';
import { PlayerIdleState } from './PlayerIdleState';
import { PlayerAttackState } from './PlayerAttackState';
import { EnemyManager } from '../EnemyManager';
import { PlayerDeathState } from './PlayerDeathState';
const { ccclass, property } = _decorator;

@ccclass('Player')
export class Player extends Entity {
    @property(Number)
    public moveSpeed: number = 12;

    @property(Number)
    public attackDamage: number = 5;

    @property({ type: Node })
    public gameOverWnd: Node = null;

    public attackCooldown: number = 3; // 攻击冷却时间
    public lastAttackTime: number = 0;

    @property(Node)
    public weapon: Node | null = null;

    _input: Vec2 = v2();
    set input(v: Vec2) { this._input.set(v.x, v.y); }
    get input(): Vec2 { return this._input; }

    public targetEnemy: Node | null = null;

    public stateMachine: PlayerStateMachine;
    public idleState: PlayerIdleState;
    public moveState: PlayerMoveState;
    public attackState: PlayerAttackState;
    public deathState: PlayerDeathState;



    public onLoad() {
        super.onLoad();
        this.stateMachine = new PlayerStateMachine();
        this.idleState = new PlayerIdleState(this, this.stateMachine);
        this.moveState = new PlayerMoveState(this, this.stateMachine);
        this.attackState = new PlayerAttackState(this, this.stateMachine);
        this.deathState = new PlayerDeathState(this, this.stateMachine);
    }

    protected override start() {
        super.start();
        this.stateMachine.Initialize(this.idleState);
    }



    protected override update(dt: number) {
        super.update(dt);
        this.stateMachine.currentState.update(dt);
        let h = VirtualInput.horizontal;
        let v = VirtualInput.vertical;
        this.input.set(h, v);
        if (VirtualInput.facingLeft) {
            this.skeleton.node.setScale(new Vec3(-0.8, 0.8, 1));
        } else {
            this.skeleton.node.setScale(new Vec3(0.8, 0.8, 1));
        }
    }

    public TakeDamage(damageToTake: number) {
        this.currentHp -= damageToTake;
        this.hpBar.updateHealth(this.currentHp, this.maxHp);
        if (this.currentHp <= 0) {
            this.stateMachine.changeState(this.deathState);
        }
    }



}


